﻿using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Windows;

using EnvDTE;

using EnvDTE80;

namespace FanaticToy.CommandCore
{
    ///<summary>创建来自解决方案资源管理器的快捷命令</summary>
    internal class CreateResourceInSolutionQuick
    {
        public void Execute(DTE2 dte)
        {
            try
            {
                var selectedItems = (IEnumerable)dte
               .ToolWindows
               .SolutionExplorer
               .SelectedItems;

                if (selectedItems == null) return;

                var projectItem = selectedItems
                    .OfType<UIHierarchyItem>()
                    .Select(i => i.Object)
                    .OfType<ProjectItem>()
                    .FirstOrDefault();

                if (projectItem == null) return;

                ExecuteCore(projectItem);
            }
            catch (System.Exception ex)
            {
                Clipboard.SetText($@"/*
{ex.Message}
*/");
            }
        }

        public void ExecuteCore(ProjectItem projItem)
        {
            var projName = GetProjectName(projItem);
            var projPath = GetProjectPath(projItem);
            var docPath = GetDocumentPath(projItem);

            if (string.IsNullOrWhiteSpace(projName)) return;
            if (string.IsNullOrWhiteSpace(projPath)) return;
            if (string.IsNullOrWhiteSpace(docPath)) return;

            var relPath = docPath.Substring(projPath.Length).Trim('/', '\\');
            var uri = $@"pack://application:,,,/{projName};component/{relPath}";
            uri =  uri.Replace('\\', '/');
            Clipboard.SetText(uri);
        }

        ///<summary>获得项目所属名。</summary>
        private string GetProjectName(ProjectItem projItem)
        {
            var containingProject = projItem.ContainingProject;

            if (containingProject == null) return string.Empty;

            return containingProject.Name;
        }

        ///<summary>获得项目所属名。</summary>
        private string GetProjectPath(ProjectItem projItem)
        {
            var containingProject = projItem.ContainingProject;

            if (containingProject == null) return string.Empty;

            return Path.GetDirectoryName(containingProject.FileName);
        }

        private string GetDocumentPath(ProjectItem projItem)
        {
            return projItem.FileNames[0];
        }

    }
}
